﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quizz.DataRepository.Models;
using System.Data.Linq;

namespace Quizz.Service.Services
{
    public class PropertyService : QuizzDomainService<QuizzDataContext>
    {
        public Property GetById(long id){
            return CompiledPropertyService.GetById(DataContext, id);
        }

        public IEnumerable<Property> GetAll(){
            return CompiledPropertyService.GetAll(DataContext);
        }

        public IEnumerable<Property> GetByType(int type){
            return CompiledPropertyService.GetByType(DataContext, type);
        }

        public Property GetByName(string name){
            return CompiledPropertyService.GetByName(DataContext, name);
        }

        public void Insert(Property property)
        {
            DataContext.Properties.InsertOnSubmit(property);
            DataContext.SubmitChanges();
        }

        public void Update(Property property){
            var sql = @"UPDATE [Property] SET [Type] = {0}, [Name] = {1}, [Value] = {2}, [title] = {3} WHERE [Id] = {4}";
            ExecuteCommand(sql, property.Type, property.Name, property.Value, property.Title, property.Id);
        }

        public void Delete(long id){
            var sql = @"DELETE [Property] WHERE [Id] = {0}";
            ExecuteCommand(sql, id);
        }

        public void Delete(Property property){
            Delete(property.Id);
        }
    }

    internal static class CompiledPropertyService {
        public static Func<QuizzDataContext, long, Property> GetById = CompiledQuery.Compile<QuizzDataContext, long, Property>((ctx, id) => ctx.Properties.FirstOrDefault(p => p.Id == id));
        public static Func<QuizzDataContext, IEnumerable<Property>> GetAll = CompiledQuery.Compile<QuizzDataContext, IEnumerable<Property>>(ctx => ctx.Properties);
        public static Func<QuizzDataContext, int, IEnumerable<Property>> GetByType = CompiledQuery.Compile<QuizzDataContext, int, IEnumerable<Property>>((ctx, type) => ctx.Properties.Where(p => p.Type == type));
        public static Func<QuizzDataContext, string, Property> GetByName = CompiledQuery.Compile<QuizzDataContext, string, Property>((ctx, name) => ctx.Properties.FirstOrDefault(p => p.Name.Equals(name)));
    }
}
